package com.originskyseed.platform.task.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.originskyseed.platform.cms.model.CmsAnchorRelateRecommend;
import com.originskyseed.platform.common.api.util.QueryAppUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.cms.service.ICmsAnchorRelateRecommendService;
import com.originskyseed.platform.common.annotation.SysLog;
import com.originskyseed.platform.common.api.util.DataUtil;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.core.util.bean.ExportExcelUtil;
import com.originskyseed.platform.course.model.Paper;
import com.originskyseed.platform.course.model.PaperRelateAnswer;
import com.originskyseed.platform.course.model.PaperRelateSubject;
import com.originskyseed.platform.course.model.PaperRelateSubjectOption;
import com.originskyseed.platform.course.model.PaperRelateUser;
import com.originskyseed.platform.course.service.ICourseService;
import com.originskyseed.platform.course.service.IPaperRelateAnswerService;
import com.originskyseed.platform.course.service.IPaperRelateSubjectOptionService;
import com.originskyseed.platform.course.service.IPaperRelateSubjectService;
import com.originskyseed.platform.course.service.IPaperRelateUserService;
import com.originskyseed.platform.course.service.IPaperService;
import com.originskyseed.platform.task.i18n.TaskResponseMsg;
import com.originskyseed.platform.task.model.SpreadLimit;
import com.originskyseed.platform.task.model.SpreadUsed;
import com.originskyseed.platform.task.model.Task;
import com.originskyseed.platform.task.model.TaskRankVO;
import com.originskyseed.platform.task.model.TaskRelateAssignPerson;
import com.originskyseed.platform.task.model.TaskRelateCourse;
import com.originskyseed.platform.task.model.TaskRelateCourseUser;
import com.originskyseed.platform.task.model.TaskRelateMaintainUser;
import com.originskyseed.platform.task.model.TaskVO;
import com.originskyseed.platform.task.service.ISpreadLimitService;
import com.originskyseed.platform.task.service.ISpreadUsedService;
import com.originskyseed.platform.task.service.ITaskRelateAssignPersonService;
import com.originskyseed.platform.task.service.ITaskRelateCompletePersonService;
import com.originskyseed.platform.task.service.ITaskRelateCourseService;
import com.originskyseed.platform.task.service.ITaskRelateCourseUserService;
import com.originskyseed.platform.task.service.ITaskRelateMaintainUserService;
import com.originskyseed.platform.task.service.ITaskService;
import com.originskyseed.platform.task.vo.request.TaskRequestVO;
import com.originskyseed.platform.user.model.Dept;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IAnchorService;
import com.originskyseed.platform.user.service.IDeptService;
import com.originskyseed.platform.user.service.IFamilyService;
import com.originskyseed.platform.user.service.IPlayerService;
import com.originskyseed.platform.user.service.ISpreadPlayerLimitService;
import com.originskyseed.platform.user.service.ITradeUnionService;
import com.originskyseed.platform.user.service.IUserInfoService;

/**
 * 任务表Controller类（OSI_TASK）
 *
 * @author wlj
 */
@Controller
@RequestMapping("/task")
@BaseLocaleResource(localeFileName = "i18n_task")
public class TaskController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(TaskController.class);

	@DubboReference
	private ITaskService taskService;

	@DubboReference
	private ITaskRelateCompletePersonService taskRelateCompletePersonService;

	@DubboReference
	private ITaskRelateMaintainUserService taskRelateMaintainUserService;

	@DubboReference
	private IUserInfoService userInfoService;

	@DubboReference
	private IDeptService deptService;

	@DubboReference
	private ITradeUnionService tradeUnionService;

	@DubboReference
	private ISpreadLimitService spreadLimitService;

	@DubboReference
	private ITaskRelateAssignPersonService taskRelateAssignPersonService;

	@DubboReference
	private ICmsAnchorRelateRecommendService cmsAnchorRelateRecommendService;

	@DubboReference
	private IAnchorService anchorService;

	@DubboReference
	private IFamilyService familyService;

	@DubboReference
	private ICourseService courseService;

	@DubboReference
	private ITaskRelateCourseService taskRelateCourseService;

	@DubboReference
	private IPlayerService playerService;

	@DubboReference
	private ITaskRelateCourseUserService taskRelateCourseUserService;

	@DubboReference
	private IPaperService paperService;

	@DubboReference
	private IPaperRelateUserService paperRelateUserService;

	@DubboReference
	private IPaperRelateSubjectService paperRelateSubjectService;

	@DubboReference
	private IPaperRelateAnswerService paperRelateAnswerService;

	@DubboReference
	private IPaperRelateSubjectOptionService paperRelateSubjectOptionService;

	@DubboReference
	private ISpreadUsedService spreadUsedService;

	@DubboReference
	private ISpreadPlayerLimitService spreadPlayerLimitService;

	/**
	 * 分页查询_接单中心
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/taskList.json")
	@RequiredParams(names = { "pageNo", "pageSize" })
	@SysLog(module = "任务广场", operationDesc = "接单中心")
	public BaseResponseBody<BasePage<Task>> taskList(HttpServletRequest request) {
		BaseResponseBody<BasePage<Task>> result = null;
		try {
			// 请求对象
			TaskRequestVO requestVO = this.getParameterBean(TaskRequestVO.class);
			if(requestVO.getPageNo()<0)
			{
				requestVO.setPageNo(1);
			}
			// 任务列表分页查询
			BasePage<Task> page = new BasePage<Task>(requestVO.getPageNo(), requestVO.getPageSize());
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			requestVO.setType(2);// 推广任务
			page = this.taskService.selectListByPage(requestVO.toMap(), page, userInfo);
			result = new BaseResponseBody<BasePage<Task>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<Task>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 任务列表_分页查询-三大平台集成接口
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/taskCenterList.json")
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<Task>> taskCenterList(HttpServletRequest request) {
		BaseResponseBody<BasePage<Task>> result = null;
		try {
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			if(userInfo==null)
			{
				result = new BaseResponseBody<BasePage<Task>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_LIST_ERROR.getMsg()), null, null);
				return  result;
			}
			// 请求对象
			TaskRequestVO requestVO = this.getParameterBean(TaskRequestVO.class);
			String fininshTimeStr = requestVO.getFinishTime();
			if (fininshTimeStr != null && StringUtils.isNotEmpty(fininshTimeStr)) {
				requestVO.setFinishTimeBegin(fininshTimeStr + " 00:00:00");
				requestVO.setFinishTimeEnd(fininshTimeStr + " 24:00:00");
			}

			// 任务列表分页查询
			BasePage<Task> page = new BasePage<Task>(requestVO.getPageNo(), requestVO.getPageSize());
			if (0==userInfo.getSourceSys()) { // OW 运管
				// 培训任务
				page = this.taskService.selectAdminListByPage(requestVO.toMap(), page, userInfo);
			} else {
				page = this.taskService.selectCenterListByPage(requestVO.toMap(), page, userInfo);
			}
			result = new BaseResponseBody<BasePage<Task>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_LIST_SUCCESS.getMsg()), page);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<Task>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 看板统计数据对应的列表
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/countTaskCenterList.json")
	@RequiredParams(names = { "pageNo", "pageSize", "dataType" }) // 1今日 2已完成 3紧急任务 4逾期任务
	public BaseResponseBody<BasePage<Task>> countTaskCenterList(HttpServletRequest request) {
		BaseResponseBody<BasePage<Task>> result = null;
		try {
			// 请求对象
			TaskRequestVO requestVO = this.getParameterBean(TaskRequestVO.class);
			Integer dataType = this.getParameterInteger("dataType", null);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 任务列表分页查询
			BasePage<Task> page = new BasePage<Task>(requestVO.getPageNo(), requestVO.getPageSize());
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if (dataType != null) {
				// 今日
				if (dataType == 1) {
					requestVO.setBeginTime(format.format(DataUtil.getStartTime()));
					requestVO.setEndTime(format.format(DataUtil.getnowEndTime()));
				}
				// 已完成
				if (dataType == 2) {
					requestVO.setState(2);
				}
				// 紧急任务
				if (dataType == 3) {
					requestVO.setPrority(2);
				}
				// 逾期任务
				if (dataType == 4) {
					requestVO.setState(3);
				}
				requestVO.setCompletePersionId(userInfo.getId());// 完成人是我ID
				page = this.taskService.selectCenterListByPage(requestVO.toMap(), page, userInfo);
			}
			result = new BaseResponseBody<BasePage<Task>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<Task>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存信息 发布任务
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/taskSave.json")
	@RequiredParams(names = {})
	public BaseResponseBody<TaskVO> taskSave(HttpServletRequest request) {
		BaseResponseBody<TaskVO> result = null;
		try {
			// 请求对象
			TaskVO task = this.getParameterBean(TaskVO.class);
			List<TaskRelateAssignPerson> taskRelateAssignPersonList = this.getParameterList("taskRelateAssignPersonList", TaskRelateAssignPerson.class);
			List<TaskRelateCourse> taskRelateCourseList = this.getParameterList("taskRelateCourseList", TaskRelateCourse.class);
			List<TaskRelateCourseUser> taskRelateCourseUserList = this.getParameterList("taskRelateCourseUserList", TaskRelateCourseUser.class);
			List<TaskRelateMaintainUser> taskRelateMaintainUserList = this.getParameterList("taskRelateMaintainUserList", TaskRelateMaintainUser.class);
			if (taskRelateAssignPersonList != null && taskRelateAssignPersonList.size() > 0) {
				task.setTaskRelateAssignPersonList(taskRelateAssignPersonList);
			}
			if (taskRelateCourseList != null && taskRelateCourseList.size() > 0) {
				task.setTaskRelateCourseList(taskRelateCourseList);
			}
			if (taskRelateMaintainUserList != null && taskRelateMaintainUserList.size() > 0) {
				task.setTaskRelateMaintainUserList(taskRelateMaintainUserList);
			}
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			if (task.getId() != null && StringUtils.isNotBlank(task.getId())) {
				this.taskService.updateByTaskVOSelective(task, userInfo);
			} else {
				// 校验推广任务主播的推广上限
				if (task.getType() == 2 && taskRelateMaintainUserList != null && taskRelateMaintainUserList.size() > 0) {
					for (TaskRelateMaintainUser relateMaintainUser : taskRelateMaintainUserList) {
						int remainNum = 0;//系统设置
						int usedNum = 0;//用户剩余
						int linkNum = task.getLinkNum();//链接数
						SpreadLimit spreadLimit = this.spreadLimitService.selectByObjId(relateMaintainUser.getUserId());
						if(spreadLimit != null){
							//启用
							if(spreadLimit.getState() == 1){
								remainNum = spreadLimit.getNum();//设置数
								linkNum = task.getLinkNum();//链接数
								//判断用户上限是否超
								SpreadUsed spreadUsed = this.spreadUsedService.selectSpreadUsedByUserId(relateMaintainUser.getUserId());
								if (spreadUsed != null) {
									usedNum = spreadUsed.getUsedNum();
									//校验是否超数
									if (usedNum + linkNum <= remainNum) {
										spreadUsed.setUsedNum(usedNum + linkNum);
										this.spreadUsedService.updateByPrimaryKeySelective(spreadUsed);
									} else {
										return new BaseResponseBody<TaskVO>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.OUT_OF_SPREAD_LIMIT_ERROR.getMsg()) + "上限数量剩余：" + (remainNum - usedNum), null);
									}
								} else {
									SpreadUsed newSpreadUsed = new SpreadUsed();
									newSpreadUsed.setObjId(relateMaintainUser.getUserId());
									newSpreadUsed.setObjName(relateMaintainUser.getName());
									newSpreadUsed.setUsedNum(linkNum);
									newSpreadUsed.setCreator(userInfo.getName());
									newSpreadUsed.setCreatorId(userInfo.getId());
									this.spreadUsedService.insertSelective(newSpreadUsed);
								}
							}
							this.taskService.insertSelectiveByTaskVOAndUserInfo(task, userInfo);
						}else { //为空添加系统默认
							SpreadLimit defaultNum = this.spreadLimitService.selectByObjId("-1");
							remainNum = defaultNum.getNum();
							if(defaultNum != null){
								if(remainNum == 0){
									return new BaseResponseBody<TaskVO>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_SAVE_ERROR.getMsg())+"上限数量剩余："+0,  null);
								}
								SpreadUsed spreadUsed = this.spreadUsedService.selectSpreadUsedByUserId(relateMaintainUser.getUserId());
								if(spreadUsed != null) {
									usedNum = spreadUsed.getUsedNum();
									if (linkNum + usedNum <= remainNum) {
										spreadUsed.setUsedNum(usedNum + linkNum);
										this.spreadUsedService.updateByPrimaryKeySelective(spreadUsed);
									}else {
										return new BaseResponseBody<TaskVO>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_SAVE_ERROR.getMsg())+"上限数量剩余："+(remainNum-usedNum),  null);
									}
								}else {
									if(linkNum > remainNum){
										return new BaseResponseBody<TaskVO>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_SAVE_ERROR.getMsg())+"系统设置数量为："+remainNum,  null);
									}
									SpreadUsed newSpreadUsed = new SpreadUsed();
									newSpreadUsed.setObjId(relateMaintainUser.getUserId());
									newSpreadUsed.setObjName(relateMaintainUser.getName());
									newSpreadUsed.setUsedNum(linkNum);
									newSpreadUsed.setCreator(userInfo.getName());
									newSpreadUsed.setCreatorId(userInfo.getId());
									this.spreadUsedService.insertSelective(newSpreadUsed);
								}
							}else {
								return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.DEFAULT_DATA_ISNULL.getMsg()), null);
							}
							this.taskService.insertSelectiveByTaskVOAndUserInfo(task, userInfo);
						}
					}
				} else {
					this.taskService.insertSelectiveByTaskVOAndUserInfo(task, userInfo);
				}
			}
			result = new BaseResponseBody<TaskVO>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_SAVE_SUCCESS.getMsg()), task);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<TaskVO>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 任务 上下架
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/taskSoldOutSave.json")
	@RequiredParams(names = {})
	public BaseResponseBody<Task> taskSoldOutSave(HttpServletRequest request) {
		BaseResponseBody<Task> result = null;
		try {
			// 请求对象
			Task task = this.getParameterBean(Task.class);
			if (task.getId() != null && StringUtils.isNotBlank(task.getId())) {
				// 推广任务增加个上下架功能 下架后 推广链接失效 上架 业务员可以重新抢单。 下架后 业务员推广任务列表 不要显示。
				this.taskService.updateByTaskId(task);
			} else {
				return new BaseResponseBody<Task>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_ID_ISNULL_ERROR.getMsg()), null);
			}
			result = new BaseResponseBody<Task>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.UPDATE_SAVE_SUCCESS.getMsg()), task);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Task>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.UPDATE_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/taskDelete.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> taskDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});
			this.taskService.deleteByPrimaryKeys(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 假删除
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/taskDeleteById.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> taskDeleteById(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});
			List<String> taskIds = Arrays.asList(ids);
			this.taskService.updateByKeys(Arrays.asList(ids));
			//补充主播上限
			if(taskIds != null && taskIds.size() >0 ){
				for (String taskId : taskIds) {
					Task task = this.taskService.selectByPrimaryKey(taskId);
					TaskRelateMaintainUser relateMaintainUser = this.taskRelateMaintainUserService.selectByTaskId(taskId);
					if(relateMaintainUser != null && relateMaintainUser.getUserId() != null && StringUtils.isNotBlank(relateMaintainUser.getUserId())){
						SpreadUsed spreadUsed = this.spreadUsedService.selectSpreadUsedByUserId(relateMaintainUser.getUserId());
						//扣减
						if(task != null && task.getLinkNum() != null && spreadUsed.getUsedNum() != null){
							spreadUsed.setUsedNum(spreadUsed.getUsedNum() - task.getLinkNum());
							this.spreadUsedService.updateByPrimaryKeySelective(spreadUsed);
						}
					}
				}
			}
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 任务列表_导出
	 *
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping(value = "/exportMytaskList.json")
	@SysLog(module = "任务广场", operationDesc = "我的任务列表信息")
	public void exportMytaskList(HttpServletRequest request, HttpServletResponse response) {
		try {
			TaskRequestVO requestVO = this.getParameterBean(TaskRequestVO.class);
			String fininshTimeStr = requestVO.getFinishTime();
			if (fininshTimeStr != null && StringUtils.isNotEmpty(fininshTimeStr)) {
				requestVO.setFinishTimeBegin(fininshTimeStr + " 00:00:00");
				requestVO.setFinishTimeEnd(fininshTimeStr + " 24:00:00");
			}
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			List<Task> list = this.taskService.selectTaskExport(requestVO.toMap(),userInfo);
			// excel标题
			String[] title = { "任务单编号", "任务单名称", "任务优先级", "任务类型", "任务状态","是否上架","推广链接数", "任务开始日期", "任务截止日期", "任务完成时间", "创建人", "指派人" };
			// excel文件名
			String fileName = "任务信息" + System.currentTimeMillis() + ".xls";
			// sheet名
			String sheetName = "任务信息";
			String[][] values = new String[list.size()][];
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					values[i] = new String[title.length];
					Task obj = list.get(i);
					values[i][0] = obj.getId();
					values[i][1] = obj.getName();
					if (obj.getPrority() != null) {
						if (obj.getPrority() == 0) {
							values[i][2] = "普通";
						} else if (obj.getPrority() == 1) {
							values[i][2] = "紧急";
						}
					} else {
						values[i][2] = "";
					}
					// 任务类型 1维护任务 2推广任务 3学习任务 4培训任务 5其他任务
					if (obj.getType() != null) {
						if (obj.getType() == 1) {
							values[i][3] = "维护任务";
						} else if (obj.getType() == 2) {
							values[i][3] = "推广任务";
						} else if (obj.getType() == 3) {
							values[i][3] = "学习任务";
						} else if (obj.getType() == 4) {
							values[i][3] = "培训任务";
						} else if (obj.getType() == 5) {
							values[i][3] = "其他任务";
						} else {
							values[i][3] = "";
						}
					} else {
						values[i][3] = "";
					}
					// 状态 0未开始 1未完成、2完成、3延期、4关闭
					if (obj.getAssignPersionState() != null) {
						if (obj.getAssignPersionState() == 0) {
							values[i][4] = "未开始";
						} else if (obj.getAssignPersionState() == 1) {
							values[i][4] = "未完成";
						} else if (obj.getAssignPersionState() == 2) {
							values[i][4] = "完成";
						} else if (obj.getAssignPersionState() == 3) {
							values[i][4] = "延期";
						} else if (obj.getAssignPersionState() == 4) {
							values[i][4] = "关闭";
						} else {
							values[i][4] = "";
						}
					} else {
						values[i][4] = "";
					}
					if (obj.getIsEnable() != null) {
						if (obj.getIsEnable() == 0) {
							values[i][5] = "否";
						} else if (obj.getIsEnable() == 1) {
							values[i][5] = "是";
						}
					} else {
						values[i][5] = "";
					}
					values[i][6] = obj.getLinkNum() == null ? "" : obj.getLinkNum().toString();
					values[i][7] = obj.getBeginTime() == null ? "" : format.format(obj.getBeginTime());
					values[i][8] = obj.getEndTime() == null ? "" : format.format(obj.getEndTime());
					values[i][9] = obj.getFinishTime() == null ? "" : format.format(obj.getFinishTime());
					values[i][10] = obj.getCreator() == null ? "" : obj.getCreator();
					values[i][11] = obj.getAssignPersionName() == null ? "" : obj.getAssignPersionName();// 指派人
				}
			}
			outPutExcel(response, title, fileName, sheetName, values);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 输出Excel
	 *
	 * @param response
	 * @param title
	 * @param fileName
	 * @param sheetName
	 * @param values
	 * @throws IOException
	 */
	private void outPutExcel(HttpServletResponse response, String[] title, String fileName, String sheetName, String[][] values) throws IOException {
		// 创建HSSFWorkbook
		HSSFWorkbook wb = ExportExcelUtil.getHSSFWorkbook(sheetName, title, values, null);
		// 将文件存到指定位置
		this.setResponseHeader(response, fileName);
		OutputStream os = response.getOutputStream();
		wb.write(os);
		os.flush();
		os.close();
	}

	/**
	 * 发送响应流方法
	 *
	 * @param response
	 * @param fileName
	 */
	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.error(e.getMessage(), e);
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error(ex.getMessage(), ex);
		}
	}

	/**
	 * 修改完成状态 --我的任务广场
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updateTaskState.json")
	@RequiredParams(names = { "taskId", "userId" })
	public BaseResponseBody updateTaskState(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			TaskRelateAssignPerson relateAssignPerson = this.getParameterBean(TaskRelateAssignPerson.class);
			if (StringUtils.isNotBlank(relateAssignPerson.getTaskId()) && StringUtils.isNotBlank(relateAssignPerson.getUserId())) {
				TaskRelateAssignPerson taskRelateAssignPerson = new TaskRelateAssignPerson();
				taskRelateAssignPerson.setTaskId(relateAssignPerson.getTaskId());
				taskRelateAssignPerson.setUserId(relateAssignPerson.getUserId());
				taskRelateAssignPerson.setIsDel(0);
				TaskRelateAssignPerson person = this.taskRelateAssignPersonService.selectByTaskTaskRelateAssignPerson(taskRelateAssignPerson);
				if (person != null) {
					relateAssignPerson.setAccount(person.getAccount());
					relateAssignPerson.setUserId(person.getUserId());
					relateAssignPerson.setName(person.getName());
					relateAssignPerson.setId(person.getId());
					relateAssignPerson.setFinishTime(new Date());
					relateAssignPerson.setState(2);// 完成
					this.taskRelateAssignPersonService.updateByPrimaryKeySelective(relateAssignPerson);
				} else {
					relateAssignPerson.setName(userInfo.getName());
					relateAssignPerson.setAccount(userInfo.getId());
					if (userInfo.getSourceSys() == 1) {
						relateAssignPerson.setUserType(2);
					} else if (userInfo.getSourceSys() == 2) {
						relateAssignPerson.setUserType(1);
					}
					relateAssignPerson.setType(1);
					relateAssignPerson.setState(2);
					relateAssignPerson.setFinishTime(new Date());
					this.taskRelateAssignPersonService.insertSelective(relateAssignPerson);
				}
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_STATE_UPDATE_SUCCESS.getMsg()), relateAssignPerson);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_STATE_UPDATE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 任务列表详情查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/selectTaskByTaskId.json")
	@RequiredParams(names = "id") // 任务
	public BaseResponseBody selectTaskByTaskId(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			String id = this.getParameterString("id", null);// 任务ID
			String userId = this.getParameterString("userId", null);// 指派人id
			TaskVO task = this.taskService.selectByTaskVOPrimaryKey(id, userId);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			//更新已读
			if(userId != null && StringUtils.isNotEmpty(userId)){
				if(userId.equals(userInfo.getId())){
					this.taskRelateAssignPersonService.taskIsRead(id,userInfo.getId());
				}
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_DATA_SUCCESS.getMsg()), task);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 通过任务ID查询指派人考卷信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/selectPaperUserAnswer.json")
	@RequiredParams(names = { "id", "paperId", "userId" })
	public BaseResponseBody selectPaperUserAnswer(HttpServletRequest request) {
		BaseResponseBody result = null;
		Map<String, Object> resultMap = new HashMap<>();
		try {
			String id = this.getParameterString("id", null);// 任务ID
			String paperId = this.getParameterString("paperId", null);
			String userId = this.getParameterString("userId", null);
			String answerNum = this.getParameterString("answerNum", null);
			PaperRelateUser relateUser = new PaperRelateUser();
			relateUser.setTaskId(id);
			relateUser.setPaperId(paperId);
			relateUser.setCreatorId(userId);
			PaperRelateUser paperRelateUser = this.paperRelateUserService.selectByPaperRelateUser(relateUser);
			// 考卷信息
			if (paperRelateUser != null) {
				Paper paper = this.paperService.selectByPrimaryKey(paperId);
				// 查询所有的题目
				PaperRelateSubject subject = new PaperRelateSubject();
				subject.setPaperId(paperRelateUser.getId());
				List<PaperRelateSubject> paperRelateSubjectList = this.paperRelateSubjectService.selectList(subject);
				for (int i = 0; i < paperRelateSubjectList.size(); i++) {
					PaperRelateSubject paperRelateSubject = paperRelateSubjectList.get(i);
					// 题目、选项、作答
					if (paperRelateSubject != null) {
						// 查询每道题的选项
						PaperRelateAnswer paperRelateAnswer = new PaperRelateAnswer();
						paperRelateAnswer.setStemId(paperRelateSubject.getId());
						paperRelateAnswer.setPaperId(paperRelateSubject.getPaperId());
						paperRelateAnswer.setCreatorId(userId);
						paperRelateAnswer.setAnswerNumber(answerNum);
						PaperRelateAnswer relateAnswer = this.paperRelateAnswerService.selectPaperRelateAnswer(paperRelateAnswer);
						// 返回
						paperRelateSubject.setPaperRelateAnswer(relateAnswer);

						// 查询题目选项
						PaperRelateSubjectOption relateSubjectOption = new PaperRelateSubjectOption();
						relateSubjectOption.setStemId(paperRelateSubject.getId());
						relateSubjectOption.setPaperId(paperRelateSubject.getPaperId());
						List<PaperRelateSubjectOption> relateSubjectOptionList = this.paperRelateSubjectOptionService.selectList(relateSubjectOption);
						paperRelateSubject.setPaperRelateSubjectOptionList(relateSubjectOptionList);
						// 返回
						paperRelateSubjectList.set(i, paperRelateSubject);
					}
				}
				// 作答人信息
				resultMap.put("paperRelateUser", paperRelateUser);
				// 考卷信息
				resultMap.put("paper", paper);
				// 题目、选项及作答人作答
				resultMap.put("paperRelateSubjectList", paperRelateSubjectList);
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.PAPER_SELECT_DATA_SUCCESS.getMsg()), resultMap);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.PAPER_SELECT_DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 我的任务 任务状态统计看板数据 开放平台总统计
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/selectStateBoardById.json")
	@RequiredParams(names = {})
	public BaseResponseBody selectStateBoardById(HttpServletRequest request) {
		BaseResponseBody result = null;
		Map<String, Integer> resultmap = new HashMap<>();
		try {
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			if(userInfo==null)
			{
				result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_DATA_STATE_VIEW_ERROR.getMsg()),null, null);
                return result;
			}
			Integer type = this.getParameterInteger("type", 1);
			// 开放平台
			if (userInfo.getSourceSys() == 0) {
				HashMap<String, Object> paramsMap = new HashMap<>();
				int countAllTask = this.taskService.owTotalData(paramsMap);// 总任务
				paramsMap.put("state", 2);
				int countAllFinishTask = this.taskService.owTotalData(paramsMap);// 总完成任务
				paramsMap.put("state", 1);
				int countAllUnFinishTask = this.taskService.owTotalData(paramsMap);// 总未完成任务
				paramsMap.put("state", 3);
				int countAllOverDueTask = this.taskService.owTotalData(paramsMap);// 总逾期任务
				resultmap.put("count", countAllTask);
				resultmap.put("countfinish", countAllFinishTask);
				resultmap.put("counturgenct", countAllUnFinishTask);
				resultmap.put("countoverdutask", countAllOverDueTask);
			} else {
				if (type != null) {
					resultmap = this.taskService.countMyTaskNum(type, userInfo);
				}
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_DATA_STATE_VIEW_SUCCESS.getMsg()), resultmap);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_DATA_STATE_VIEW_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 任务完成趋势图形数据
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getTaskLineChar.json")
	@RequiredParams(names = "type") // type：1 日 、 2、 周 、 3、 月
	public BaseResponseBody getTaskLineChar(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			Integer type = this.getParameterInteger("type", 1);
			Map<String, Object> resultMap = new HashMap<>();// 返回页面数据
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat dateFormatDay = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if (type == 1) {
				// 今天统计数
				Map<String, Object> map2 = new HashMap();
				map2.put("user_id", userInfo.getId());
				map2.put("state", 2);// 完成
				map2.put("startTime", dateFormatDay.format(DataUtil.getStartTime()));
				map2.put("endTime", dateFormatDay.format(DataUtil.getnowEndTime()));
				Map<String, Object> todayStat = this.taskService.getTaskHourStat(map2);// 今天完成的统计数据
				map2.put("state", 1);// 未完成
				Map<String, Object> todayUnFinishStat = this.taskService.getTaskHourStat(map2);// 今天未完成的统计数据
				map2.put("state", 3);// 逾期
				Map<String, Object> todayOverduStat = this.taskService.getTaskHourStat(map2);// 今天逾期的统计数据
				map2.put("state", 2);// 完成
				map2.put("startTime", dateFormatDay.format(DataUtil.getyesterDayStartTime()));
				map2.put("endTime", dateFormatDay.format(DataUtil.getyesterDayEndTime()));
				Map<String, Object> yesterdayStat = this.taskService.getTaskHourStat(map2);// 昨天完成的统计数据
				// 算增长率
				Integer yesterdayTotalNum = (Integer) yesterdayStat.get("totalCount");// 昨天总数
				Integer todayTotalNum = (Integer) todayStat.get("totalCount");// 今天总数
				double rateNumer = 0.0;
				if (yesterdayTotalNum != 0) {
					rateNumer = (double) (todayTotalNum - yesterdayTotalNum) / yesterdayTotalNum * 100;
				} else {
					// 昨天是零
					rateNumer = todayTotalNum * 100;
				}
				BigDecimal format = new BigDecimal(rateNumer);
				rateNumer = format.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();// 四舍五入 返回值
				resultMap.put("lastTotalNum", yesterdayTotalNum);// 昨天总数
				resultMap.put("rateNumer", rateNumer);// 增长率
				resultMap.put("maxTaskNumber", todayStat.get("maxTaskNum"));
				resultMap.put("finishStat", todayStat.get("statList"));
				resultMap.put("unFinishStat", todayUnFinishStat.get("statList"));
				resultMap.put("overDuStat", todayOverduStat.get("statList"));
			}

			if (type == 2) {
				// 周数据
				Date nowweekbegindate = DataUtil.getCurrentWeekDateBegin(new Date());// 本周开始日期
				Map<String, Object> map3 = new HashMap();
				map3.put("user_id", userInfo.getId());
				map3.put("state", 2);// 完成
				map3.put("startTime", dateFormat.format(DataUtil.getCurrentFirstDayOrLastWeekFirstDay(new Date())));
				map3.put("endTime", dateFormat.format(new Date()));
				Map<String, Object> weekFinishStat = this.taskService.getTaskWeekStat(map3, nowweekbegindate);// 周完成
				map3.put("state", 1);// 未完成
				Map<String, Object> weekUnFinishStat = this.taskService.getTaskWeekStat(map3, nowweekbegindate);// 周未完成
				map3.put("state", 3);// 逾期
				Map<String, Object> weekOverduStat = this.taskService.getTaskWeekStat(map3, nowweekbegindate);// 周逾期
				map3.put("state", 2);// 完成
				map3.put("startTime", dateFormat.format(DataUtil.getLastWeekDateFirstDayOrBeforeLastFirstDay(new Date())));
				map3.put("endTime", dateFormat.format(DataUtil.getLastWeekDate(new Date())));// 上周同期时间
				Map<String, Object> lastweekFinishStat = this.taskService.getTaskWeekStat(map3, DataUtil.getLastWeekDateBegin(new Date()));// 上周完成统计
				// 算增长率
				Integer lastWeekTotalNum = (Integer) lastweekFinishStat.get("weektotalCount");// 同期上周总数
				Integer weekTotalNum = (Integer) weekFinishStat.get("weektotalCount");// 本周总数
				double weekrateNumer = 0.0;
				if (lastWeekTotalNum != 0) {
					weekrateNumer = (double) (weekTotalNum - lastWeekTotalNum) / lastWeekTotalNum * 100;
				} else {
					// 昨天是零
					weekrateNumer = weekTotalNum * 100;
				}
				BigDecimal weekformat = new BigDecimal(weekrateNumer);
				weekrateNumer = weekformat.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();// 四舍五入 返回值

				// 返回数据
				resultMap.put("lastTotalNum", lastWeekTotalNum);// 同期上周总数
				resultMap.put("rateNumer", weekrateNumer);// 增长率
				resultMap.put("maxTaskNumber", weekFinishStat.get("weekmaxTaskNum"));// 本周最大值
				resultMap.put("finishStat", weekFinishStat.get("weekMap"));// 完成
				resultMap.put("unFinishStat", weekUnFinishStat.get("weekMap"));// 未完成
				resultMap.put("overDuStat", weekOverduStat.get("weekMap"));// 逾期
			}

			if (type == 3) {
				// 月数据
				Date dateBegin = DataUtil.getCurrentMonthDateBegin(new Date());// 本月开始日期
				Date dateEnd = DataUtil.getCurrentMonthDateEnd(new Date());// 本月最后一天
				Date lastMonthDateBegin = DataUtil.getLastMonthDateBegin(new Date());// 上个月开始日期
				Date lastMonthDate = DataUtil.getLastMonthDate(new Date());// 同期上个月开始日期
				Map<String, Object> map4 = new HashMap();
				map4.put("user_id", userInfo.getId());
				map4.put("state", 2);// 完成
				map4.put("startTime", dateFormat.format(dateBegin));
				map4.put("endTime", dateFormat.format(new Date()));
				Map<String, Object> monthFinishStat = this.taskService.getTaskMonthStat(map4, dateBegin, dateEnd);// 完成
				map4.put("state", 1);// 未完成
				Map<String, Object> monthUnFinishStat = this.taskService.getTaskMonthStat(map4, dateBegin, dateEnd);
				map4.put("state", 3);// 逾期
				Map<String, Object> monthOvergueStat = this.taskService.getTaskMonthStat(map4, dateBegin, dateEnd);
				map4.put("state", 2);// 完成
				map4.put("startTime", dateFormat.format(lastMonthDateBegin));// 上个月开始日期
				map4.put("endTime", dateFormat.format(lastMonthDate));// 上个月同期日期
				Map<String, Object> lastMonthStat = this.taskService.getTaskMonthStat(map4, DataUtil.getLastMonthDateBegin(new Date()), DataUtil.getLastMonthDateEnd(new Date()));
				// 算增长率
				Integer lastMonthTotalNum = (Integer) lastMonthStat.get("monthtotalCount");// 同期上个月总数
				Integer monthTotalNum = (Integer) monthFinishStat.get("monthtotalCount");// 本周总数
				double monthrateNumer = 0.0;
				if (lastMonthTotalNum != 0) {
					monthrateNumer = (double) (monthTotalNum - lastMonthTotalNum) / lastMonthTotalNum * 100;
				} else {
					monthrateNumer = monthTotalNum * 100;
				}
				BigDecimal monthformat = new BigDecimal(monthrateNumer);
				monthrateNumer = monthformat.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();// 四舍五入 返回值

				// 返回数据
				resultMap.put("lastTotalNum", lastMonthTotalNum);
				resultMap.put("rateNumer", monthrateNumer);
				resultMap.put("maxTaskNumber", monthFinishStat.get("monthmaxTaskNum"));// 月峰值
				resultMap.put("finishStat", monthFinishStat.get("monthMap"));
				resultMap.put("unFinishStat", monthUnFinishStat.get("monthMap"));
				resultMap.put("overDuStat", monthOvergueStat.get("monthMap"));
			}

			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_DATA_STATE_VIEW_SUCCESS.getMsg()), resultMap);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_DATA_STATE_VIEW_ERROR.getMsg()), null);
		}
		return result;
	}

	/**
	 * 业务员/主播任务完成情况看板 集成开发
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getTaskLineToSaleManAndAnchor.json")
	@RequiredParams(names = "type") // type：1 日 、 2、 周 、 3、 月
	public BaseResponseBody getTaskLineToSaleManAndAnchor(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			Integer type = this.getParameterInteger("type", 1);
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat dateFormatDay = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Map<String, Object> resultMap = new HashMap<>();// 返回页面数据
			// if (userInfo.getSourceSys() == 1 && (userInfo.getType() == 5 || userInfo.getType() == 4 || userInfo.getType() == 3 || userInfo.getType() == 2)|| userInfo.getSourceSys() == 2 &&(userInfo.getType() == 5 || userInfo.getType() ==2)) {
			if (type == 1) { // 日数据
				Map<String, Object> map = new HashMap<>();
				map.put("state", 2);// 完成
				map.put("startTime", dateFormatDay.format(DataUtil.getStartTime()));
				map.put("endTime", dateFormatDay.format(DataUtil.getnowEndTime()));
				Map<String, Object> todayStat = this.taskService.getTaskHourStatByAnchorAndSaleMan(map, userInfo);// 完成
				map.put("state", 3);// 延期
				Map<String, Object> todayOverduStat = this.taskService.getTaskHourStatByAnchorAndSaleMan(map, userInfo);
				// 昨天完成
				map.put("state", 2);// 完成
				map.put("startTime", dateFormatDay.format(DataUtil.getyesterDayStartTime()));
				map.put("endTime", dateFormatDay.format(DataUtil.getyesterDayEndTime()));
				Map<String, Object> yesterdayStat = this.taskService.getTaskHourStatByAnchorAndSaleMan(map, userInfo);// 昨天完成的统计数据
				// 算完成增长率
				Integer yesterdayTotalNum = (Integer) yesterdayStat.get("totalCount");// 昨天总数
				Integer todayTotalNum = (Integer) todayStat.get("totalCount");// 今天总数
				double rateNumer = 0.0;
				if (yesterdayTotalNum != 0) {
					rateNumer = (double) (todayTotalNum - yesterdayTotalNum) / yesterdayTotalNum * 100;
				} else {
					// 昨天是零
					rateNumer = todayTotalNum * 100;
				}
				BigDecimal format = new BigDecimal(rateNumer);
				rateNumer = format.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();// 四舍五入 返回值
				resultMap.put("rateNumer", rateNumer);// 同比昨天增长率
				resultMap.put("countFinishStat", todayStat.get("totalCount"));
				resultMap.put("countOverDuStart", todayOverduStat.get("totalCount"));
				resultMap.put("finishStat", todayStat.get("statList"));
				resultMap.put("overDuStat", todayOverduStat.get("statList"));
			}

			if (type == 2) { // 周数据
				Map<String, Object> map = new HashMap<>();
				map.put("state", 2);// 完成
				map.put("startTime", dateFormat.format(DataUtil.getCurrentFirstDayOrLastWeekFirstDay(new Date())));
				map.put("endTime", dateFormat.format(new Date()));
				Map<String, Object> weekStat = this.taskService.getTaskWeekStatToSaleManOrAnchor(map, userInfo);// 完成
				map.put("state", 3);// 延期
				Map<String, Object> weekOverduStat = this.taskService.getTaskWeekStatToSaleManOrAnchor(map, userInfo);
				// 上周完成
				map.put("state", 2);// 完成
				map.put("startTime", dateFormat.format(DataUtil.getLastWeekDateFirstDayOrBeforeLastFirstDay(new Date())));
				map.put("endTime", dateFormat.format(DataUtil.getLastWeekDate(new Date())));// 上周同期时间
				Map<String, Object> lastWeekStat = this.taskService.getTaskWeekStatToSaleManOrAnchor(map, userInfo);// 昨天完成的统计数据
				// 算完成增长率
				Integer yesterdayTotalNum = (Integer) lastWeekStat.get("weektotalCount");// 昨天总数
				Integer todayTotalNum = (Integer) weekStat.get("weektotalCount");// 今天总数
				double rateNumer = 0.0;
				if (yesterdayTotalNum != 0) {
					rateNumer = (double) (todayTotalNum - yesterdayTotalNum) / yesterdayTotalNum * 100;
				} else {
					// 昨天是零
					rateNumer = todayTotalNum * 100;
				}
				BigDecimal format = new BigDecimal(rateNumer);
				rateNumer = format.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();// 四舍五入 返回值
				resultMap.put("rateNumer", rateNumer);// 同比昨天增长率
				resultMap.put("countFinishStat", weekStat.get("weektotalCount"));
				resultMap.put("countOverDuStart", weekOverduStat.get("weektotalCount"));
				resultMap.put("finishStat", weekStat.get("weekMap"));
				resultMap.put("overDuStat", weekOverduStat.get("weekMap"));
			}
			if (type == 3) { // 月数据
				Date dateBegin = DataUtil.getCurrentMonthDateBegin(new Date());// 本月开始日期
				Date dateEnd = DataUtil.getCurrentMonthDateEnd(new Date());// 本月最后一天
				Date lastMonthDateBegin = DataUtil.getLastMonthDateBegin(new Date());// 上个月开始日期
				Date lastMonthDate = DataUtil.getLastMonthDate(new Date());// 同期上个月开始日期
				Map<String, Object> map = new HashMap<>();
				map.put("state", 2);// 完成
				map.put("startTime", dateFormat.format(dateBegin));
				map.put("endTime", dateFormat.format(new Date()));
				Map<String, Object> monthStat = this.taskService.getTaskMonthStatToSaleManOrAnchor(map, dateBegin, dateEnd, userInfo);// 完成
				map.put("state", 3);// 延期
				Map<String, Object> monthOverduStat = this.taskService.getTaskMonthStatToSaleManOrAnchor(map, dateBegin, dateEnd, userInfo);
				// 上个月完成
				map.put("state", 2);// 完成
				map.put("startTime", dateFormat.format(lastMonthDateBegin));// 上个月开始日期
				map.put("endTime", dateFormat.format(lastMonthDate));// 上个月同期日期
				Map<String, Object> lastMonthStat = this.taskService.getTaskMonthStatToSaleManOrAnchor(map, dateBegin, dateEnd, userInfo);// 昨天完成的统计数据
				// 算完成增长率
				Integer yesterdayTotalNum = (Integer) lastMonthStat.get("monthtotalCount");// 昨天总数
				Integer todayTotalNum = (Integer) monthStat.get("monthtotalCount");// 今天总数
				double rateNumer = 0.0;
				if (yesterdayTotalNum != 0) {
					rateNumer = (double) (todayTotalNum - yesterdayTotalNum) / yesterdayTotalNum * 100;
				} else {
					// 昨天是零
					rateNumer = todayTotalNum * 100;
				}
				BigDecimal format = new BigDecimal(rateNumer);
				rateNumer = format.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();// 四舍五入 返回值
				resultMap.put("rateNumer", rateNumer);// 同比昨天增长率
				resultMap.put("countFinishStat", monthStat.get("monthtotalCount"));
				resultMap.put("countOverDuStart", monthOverduStat.get("monthtotalCount"));
				resultMap.put("finishStat", monthStat.get("monthMap"));
				resultMap.put("overDuStat", monthOverduStat.get("monthMap"));
			}
			// }
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_DATA_STATE_VIEW_SUCCESS.getMsg()), resultMap);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_DATA_STATE_VIEW_ERROR.getMsg()), null);
		}
		return result;
	}

	/**
	 * 开放平台_公会、家族体系看板数据
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/countSystemLineData.json")
	@RequiredParams(names = { "type", "objType" }) // 1-日 2-周 3-月 objType: 1 公会 2家族
	public BaseResponseBody countSystemLineData(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			Integer type = this.getParameterInteger("type", 1);
			Integer objType = this.getParameterInteger("objType", 1);
			if (type != null && objType != null) {
				Dept dept = new Dept();
				if (objType == 1) { // 公会体系
					dept.setSourceSys(2);
					dept.setType(1);
				} else { // 家族体系
					dept.setSourceSys(1);
					dept.setType(1);
				}
				Map<String, Object> resultMap = this.taskService.countSystemBytypeAndDept(type, dept);
				result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_DATA_STATE_VIEW_SUCCESS.getMsg()), resultMap);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_DATA_STATE_VIEW_ERROR.getMsg()), null);
		}
		return result;
	}

	/**
	 * 导出体系任务统计中的数据
	 *
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping(value = "/countSystemLineDataToExcel.json")
	@SysLog(module = "任务广场", operationDesc = "体系任务统计数据导出")
	public void countSystemLineDataToExcel(HttpServletRequest request, HttpServletResponse response) {
		try {
			Integer type = this.getParameterInteger("type", 1);
			Integer objType = this.getParameterInteger("objType", 1);
			List<Map<String, Object>> list = new ArrayList<>();
			if (type != null && objType != null) {
				Dept dept = new Dept();
				if (objType == 1) { // 公会体系
					dept.setSourceSys(2);
					dept.setType(1);
				} else { // 家族体系
					dept.setSourceSys(1);
					dept.setType(8);
				}
				Map<String, Object> resultMap = this.taskService.countSystemBytypeAndDept(type, dept);
				Object finish = resultMap.get("finishList");// 完成
				if (finish instanceof List) {
					List<Map<String, Object>> finishList = (List<Map<String, Object>>) finish;
					for (Map<String, Object> objectMap : finishList) {
						objectMap.put("state", "完成");
						list.add(objectMap);
					}
				}
				Object unFinish = resultMap.get("unFinishList");// 未完成
				if (unFinish instanceof List) {
					List<Map<String, Object>> unFinishList = (List<Map<String, Object>>) unFinish;
					for (Map<String, Object> objectMap : unFinishList) {
						objectMap.put("state", "未完成");
						list.add(objectMap);
					}
				}
				Object overdue = resultMap.get("overdueList");// 逾期
				if (overdue instanceof List) {
					List<Map<String, Object>> overdueList = (List<Map<String, Object>>) overdue;
					for (Map<String, Object> objectMap : overdueList) {
						objectMap.put("state", "逾期");
						list.add(objectMap);
					}
				}

			}

			// excel标题
			String[] title = { "体系名称", "任务数量", "状态" };
			// excel文件名
			String fileName = "体系任务状态信息" + System.currentTimeMillis() + ".xls";
			// sheet名
			String sheetName = "体系任务状态信息";
			String[][] values = new String[list.size()][];

			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					values[i] = new String[title.length];
					Map<String, Object> obj = list.get(i);
					values[i][0] = obj.get("xAxis") == null ? "" : obj.get("xAxis").toString();
					values[i][1] = obj.get("yAxis") == null ? "" : obj.get("yAxis").toString();
					values[i][2] = obj.get("state") == null ? "" : obj.get("state").toString();
				}
			}
			outPutExcel(response, title, fileName, sheetName, values);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 任务完成排行榜单
	 */
	@ResponseBody
	@RequestMapping(value = "/rankingList.json")
	@RequiredParams(names = { "type" })
	@SysLog(module = "任务广场", operationDesc = "任务完成排行榜")
	public BaseResponseBody rankingList(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			Integer type = this.getParameterInteger("type", null);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			HashMap<String, Object> resultMap = new HashMap<>();
			HashMap<String, Object> map = new HashMap<>();// 条件
			if (type == 1) {
				map.put("state", 2);// 完成
			} else if (type == 2) {
				map.put("state", 3);// 逾期
			}
			if (userInfo.getSourceSys() == 1) { // 主播
				map.put("userType", 11);
			} else {
				map.put("userType", 6);
			}
			// 我的排名
			List<TaskRankVO> myRankList = this.taskService.selectRankList(map);
			int myRank = 0;
			if (myRankList != null && myRankList.size() > 0) {
				for (int i = 0; i < myRankList.size(); i++) {
					TaskRankVO taskRankVO = myRankList.get(i);
					if (taskRankVO.getUserId().equals(userInfo.getId())) {
						myRank = i + 1;
						break;
					}
				}
			}
			// 排名列表
			map.put("limit", 3);
			List<TaskRankVO> rankList = this.taskService.selectRankList(map);
			resultMap.put("myranknum", myRank);// 我的排名
			resultMap.put("rankList", rankList);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.SELECT_RANKING_SUCCESS.getMsg()), resultMap);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.SELECT_RANKING_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 任务广场_抢单
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/taskRelateCompletePersonSave.json")
	@RequiredParams(names = { "taskId", "anchorId" }) // 任务单ID、主播ID
	@SysLog(module = "任务广场", operationDesc = "抢单")
	public BaseResponseBody taskRelateCompletePersonSave(HttpServletRequest request) {
		BaseResponseBody result = null;
		TreeMap<String, Object> paramMap = new TreeMap<>();
		try {
			// 请求对象
			String taskId = this.getParameterString("taskId", null);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			if (userInfo.getSourceSys() == 2 && (userInfo.getType() == 6 || StringUtils.isNotBlank(userInfo.getOtherAccount()))) { // 业务员
				// 校验业务员推广上限数量
				SpreadLimit spreadLimit = this.spreadLimitService.selectByObjId(userInfo.getId());
				if (spreadLimit == null) {
					// 没有就选系统默认
					spreadLimit = this.spreadLimitService.selectByObjId("-2");//业务员的默认推广上限
				}
				if (spreadLimit != null) {
					int num = spreadLimit.getNum();

					SpreadUsed spreadUsed = spreadUsedService.selectSpreadUsedByUserId(userInfo.getId());
					boolean res = true;
					if (spreadUsed == null) {
						if (num == 0) {
							return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.OUT_OF_SPREAD_LIMIT_ERROR.getMsg()), null);
						} else {
							res = true;
							SpreadUsed tempSpreadUsed = new SpreadUsed();
							tempSpreadUsed.setUsedNum(1);
							tempSpreadUsed.setObjId(userInfo.getId());
							tempSpreadUsed.setObjName(userInfo.getName());
							tempSpreadUsed.setCreator(userInfo.getName());
							tempSpreadUsed.setCreatorId(userInfo.getId());
							spreadUsedService.insertSelective(tempSpreadUsed);
						}
					} else {
						int useNum = spreadUsed.getUsedNum();
						if (useNum + 1 <= num) {
							res = true;
							spreadUsed.setUsedNum(useNum + 1);
							spreadUsedService.updateByPrimaryKeySelective(spreadUsed);
						} else {
							return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.OUT_OF_SPREAD_LIMIT_ERROR.getMsg()), null);
						}
					}
					if (res) {
						TaskRelateAssignPerson taskRelateAssignPerson = new TaskRelateAssignPerson();
						taskRelateAssignPerson.setUserId(userInfo.getId());
						taskRelateAssignPerson.setName(userInfo.getName());
						taskRelateAssignPerson.setTaskId(taskId);
						taskRelateAssignPerson.setAccount(userInfo.getAccount());
						taskRelateAssignPerson.setType(2);// 抢单
						taskRelateAssignPerson.setState(1);
						taskRelateAssignPerson.setUserType(2);
						this.taskRelateAssignPersonService.insertSelective(taskRelateAssignPerson);
						//校验这个任务是否达到接单上限
						Task task = this.taskService.selectByPrimaryKey(taskId);
						if (task != null && task.getLinkNum() != null) {
							int taskNum = task.getLinkNum();
							// 查询已接单数量
							List<TaskRelateAssignPerson> relateAssignPersonList = this.taskRelateAssignPersonService.selectListByTaskId(taskId);
							if (relateAssignPersonList != null && relateAssignPersonList.size() > 0) {
								if (relateAssignPersonList.size() >= taskNum) {
									task.setIsReach(1);
									this.taskService.updateByPrimaryKeySelective(task);
								}
							}
						}

						String anchorUserId = this.getParameterString("anchorId", null);
						if(anchorUserId!=null&&StringUtils.isNotBlank(anchorUserId)) {
							UserInfo anchorUserInfo = userInfoService.selectByPrimaryKey(anchorUserId);
							String anchorId = anchorUserInfo == null ? "" : anchorUserInfo.getOtherAccount();
							if (anchorId != null&&StringUtils.isNotBlank(anchorId)) {
								//一旦抢单成功，需要向青芒推送业务员和主播的信息，以其生成推广链接

								paramMap.put("anchorId", anchorUserInfo.getOtherAccount());
								paramMap.put("channelId", userInfo.getOtherAccount());
								paramMap.put("loginName", userInfo.getName());
								Map resultMap = QueryAppUtil.query("invitationLinkUrl", 2, paramMap);
								Integer code = Integer.parseInt(resultMap.get("code").toString());
								String msg = (String) resultMap.get("msg");
								if (code == 1) {
									CmsAnchorRelateRecommend cmsAnchorRelateRecommend = new CmsAnchorRelateRecommend();
									cmsAnchorRelateRecommend.setAnchorUserId(anchorUserId);
									cmsAnchorRelateRecommend.setAnchorId(anchorId);
									cmsAnchorRelateRecommend.setBusinessId(userInfo.getId());
									cmsAnchorRelateRecommend.setChannelSubId(userInfo.getOtherAccount());
									cmsAnchorRelateRecommend.setTaskId(taskId);
									cmsAnchorRelateRecommend.setIsDel(2);
									cmsAnchorRelateRecommendService.insertAnchorRelateRecommend(cmsAnchorRelateRecommend);
								}
								else
								{
									return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), msg, null);
								}
							}
						}
						result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_GRAD_SUCCESS.getMsg()), true);
					}
				} else {
					return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.DEFAULT_DATA_ISNULL.getMsg()), null);
				}
			} else {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.IS_NOT_RIGHT_ERROR.getMsg()), null);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			logger.error("==invitationLinkUrl="+paramMap);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.TASK_GRAD_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询所有deptId子集
	 *
	 * @param parentCode
	 * @param list
	 * @throws Exception
	 */
	private void selectDeptSon(String parentCode, List<String> list) throws Exception {
		List<Dept> deptList = this.deptService.selectByParentCode(parentCode);

		if (deptList != null) {
			for (Dept dept1 : deptList) {
				list.add(dept1.getId());
				selectDeptSon(dept1.getCode(), list);
			}
		}
	}

}
